package com.bxl.chooser.oper.impl;

import com.bxl.chooser.bean.AppInfo;
import com.bxl.chooser.bean.ChooseMsg;
import com.bxl.chooser.bean.ChooseResponseMsg;
import com.bxl.chooser.bean.MessageBean;
import com.bxl.chooser.context.ChooserContext;
import com.bxl.chooser.factory.ChooseMsgFactory;
import com.bxl.chooser.factory.MessageBeanFactory;
import com.bxl.chooser.oper.IOperSv;
import com.bxl.chooser.oper.OperDefine;
import com.bxl.netty.rpc.client.common.client.ClientInfo;
import com.bxl.netty.rpc.common.message.PackageMsg;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

/**
 * 选举服务
 *
 * @author baixl
 * @date 2021/3/25
 */
public class QueryMessageService implements IOperSv<ChooseResponseMsg> {
    private Logger logger = LoggerFactory.getLogger(QueryMessageService.class);

    @Override
    public ChooseResponseMsg oper(PackageMsg<ChooseMsg> msg, ChooserContext context) {
        try {
            AppInfo appInfo = context.getAppInfo();
            MessageBean messageBean = appInfo.getMsg(msg.getContent().getMessageId());
            if (appInfo.getState() == AppInfo.AppState.LEADER) {

                if (messageBean == null) {
                    return ChooseMsgFactory.createChooseResponseMsg("1000", "成功", "", "");
                } else {
                    return ChooseMsgFactory.createChooseResponseMsg("1000", "成功", messageBean.getMessageId(), messageBean.getContent());
                }
            } else {
                //不是leader，切消息未提交
                if (messageBean == null || messageBean.getIndex() > appInfo.getCommitLogIndex()) {
                    if (!context.getHasLeader()) {
                        return ChooseResponseMsg.retry;
                    }
                    ClientInfo leader = context.getLeader();
                    ChooseResponseMsg.change.setLeaderIP(leader.getIp());
                    ChooseResponseMsg.change.setPort(leader.getPort());
                    return ChooseResponseMsg.change;
                } else {
                    return ChooseMsgFactory.createChooseResponseMsg("1000", "成功", messageBean.getMessageId(), messageBean.getContent());
                }
            }

        } catch (Exception e) {
            logger.error("消息写入失败");
        }
        //数据写入失败
        return ChooseResponseMsg.fail;
    }
}
